<?php
require_once './config.php';
require_once './facebook.php';
require_once './util.php';
require_once './friend.php';
//require_once './friends.php';
require_once './facebookAPIHelper.php';

session_start();

$facebook = new Facebook(array(
    'appId' => FB_APP_ID,
    'secret' => FB_APP_SECRET,
    'cookie' => true
));
if(!empty($_SESSION)){
    $facebook->setSession($_SESSION);
}

$data = null;
try{
    
    $query1 = "select thread_id, recipients from thread where folder_id = 0 or folder_id = 1 and updated_time > ".QUERY_SINCE;
    
    $query2 = "select thread_id, author_id from message where thread_id in (
    	select thread_id from #query1
	) and created_time > ".QUERY_SINCE;

    $response = null; 
    $response = callMultiFQL(array(
        'query1' => $query1,
        'query2' => $query2
    ));
    
    $threads = $response[0]['fql_result_set'];
    $messages = $response[1]['fql_result_set'];

    $threadData = array();
    foreach($threads as $thread){
        if(!array_key_exists($thread['thread_id'], $threadData)){

            $threadData[$thread['thread_id']]['sender'] = $thread['recipients'][0];
            
            if($thread['recipients'][0] == $_SESSION['uid']){
                $threadData[$thread['thread_id']]['recipients'] = array_slice($thread['recipients'], 1);                    
            } else {
                $threadData[$thread['thread_id']]['recipients'] = array($_SESSION['uid']);
            }

        }
    }
    
    $repliers = array();
    foreach($messages as $message){
        if(array_key_exists($message['thread_id'], $repliers)){
            //add replier
            array_push($repliers[$message['thread_id']], $message['author_id']);
        }else{
            //create an array
            $repliers[$message['thread_id']] = array($message['author_id']);
        }
    }
    
    $friends = array();
    foreach($threadData as $thread_id => $thread){
        //if sender is oneself
        if($thread['sender'] == $_SESSION['uid']){
            foreach($thread['recipients'] as $recipient){
                if(!array_key_exists($recipient, $friends)){
                    $friends[$recipient] = new Friend($recipient, "");
                }
                if(array_key_exists($thread_id, $repliers) && array_search($recipient, $repliers[$thread_id])){
                    $friends[$recipient]->increaseTwoway();
                } else {
                    $friends[$recipient]->increaseOneway();
                }
            }
        }else{
        //if sender is a friend, try to find myself among the repliers otherwise the sender count one-way
            if(!array_key_exists($thread['sender'], $friends)){
                $friends[$thread['sender']] = new Friend($thread['sender'], "");
            }
            if(array_key_exists($thread_id, $repliers) && array_search($_SESSION['uid'], $repliers[$thread_id])){
                $friends[$thread['sender']]->increaseTwoway();
            } else {
                $friends[$thread['sender']]->increaseOneway();
            }
        }
    }

    //sort
    uasort($friends, 'cmp');       
    
    //JSON encoding
    $json = "[";

    $isFirst = true;
    foreach($friends as $f){
        if(!$isFirst){
            $json .= ',';
        }
        $json .= '{';
        $json .= '"fId" : "'.$f->getfId().'",';
        $json .= '"oneWay" : "'.$f->getOneway().'",';
        $json .= '"twoWay" : "'.$f->getTwoway().'"';
        $json .= '}';
        $isFirst = false;
    }

    $json .= "]";

    //return output
    print $json;
        
} catch (FacebookApiException $e){
    error_log($e);
}